﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WXY.Course.BLL;
using WXY.Course.Common.MVCExtension;
using WXY.Course.Model;
using WXY.Course.Web.Areas.Admin.Filter;

namespace WXY.Course.Web.Areas.Admin.Controllers
{
    public class ModuleController : Controller
    {
        private ModuleBLL _moduleBLL = new ModuleBLL();

        public ActionResult List(int? page, string name, DateTime? beginTime, DateTime? endTime)
        {
            if (!page.HasValue) page = 1;
            if (endTime.HasValue) endTime = endTime.Value.AddDays(1);

            PageParams pageParams=new PageParams
            {
                PageIndex = page.Value,
                PageSize = 10,
                BeginTime = beginTime,
                EndTime = endTime,
                IsNeedRecordCount = true
            };

            PageViewModel<ModuleInfo> pageViewModel = new PageViewModel<ModuleInfo>();

            pageViewModel.Value = _moduleBLL.GetPageList(name, pageParams);
            pageViewModel.PageInfo = PageInfo.Create(pageParams.PageIndex, pageParams.PageSize);
            pageViewModel.PageInfo.RecordCount = pageParams.RecordCount;

            return View(pageViewModel);
        }

        public ActionResult Edit(int? id)
        {
            if (id.HasValue)
            {
                var info = _moduleBLL.Get(id.Value);
                return View(info);
            }
            return View();
        }
        [HttpPost]
        public ActionResult Edit(ModuleInfo module)
        {
            if (!ModelState.IsValid)
            {
                return View(module);
            }

            bool editResult = false;
            if (module.Code.HasValue)
            {
                editResult = _moduleBLL.Update(module) > 0;
            }
            else
            {
                editResult = _moduleBLL.Insert(module) > 0;
            }

            if (editResult)
            {
                return RedirectToAction("List");
            }
            return View(module);
        }

        [HttpPost]
        [JsonExceptionFilter(typeof(ResourceController), JsonRequestBehavior.AllowGet)]
        public JsonResult Delete(int id)
        {

            var result = new BoolResult<int>
            {
                IsSuccess = true,
                Data = _moduleBLL.Delete(id)
            };
            return Json(result, JsonRequestBehavior.AllowGet);
        }
    }
}
